import React, { useEffect, useState  } from 'react';
import { Table, Button, Modal, message, Tag, Space } from 'antd';
import { observer } from 'mobx-react-lite';
import { functionStore } from './store/functionStore';
import { EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import FunctionForm from './FunctionForm';
import {Function, FunctionType, FunctionStatus } from './store/functionTypes';


const FunctionList: React.FC = observer(() => {
  useEffect(() => {
    functionStore.fetchFunctions();
  }, []);

  const [viewType, seViewType] = useState<'create' | 'edit' | 'view'>('create');

  const handleCreate = () => {
    seViewType('create');
    functionStore.showCreateModal();
  };

  const handleView = (func: any) => {
    seViewType('view');
    functionStore.showEditModal(func);
  };

  const handleEdit = (func: any) => {
    seViewType('edit');
    functionStore.showEditModal(func);
  };


  const statusToChinese: Record<FunctionStatus, string> = {
    [FunctionStatus.DRAFT]: '草稿',
    [FunctionStatus.PUBLISHED]: '已发布',
    [FunctionStatus.DEPRECATED]: '已弃用',
    [FunctionStatus.ARCHIVED]: '已归档'
  };

  const typeToChinese: Record<FunctionType, string> = {
    [FunctionType.SYSTEM]: '系统函数',
    [FunctionType.DIRECT]: '前端函数',
    [FunctionType.PLUGIN]: '插件函数',
    [FunctionType.CUSTOM]: '自定义函数'
  };

  const handleDelete = async (id: string) => {
    try {
      await functionStore.deleteFunction(id);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async (values: any) => {
    try {
      await functionStore.saveFunction(values);
      message.success('保存成功');
    } catch (error) {
      message.error('保存失败');
    }
  };

  const columns = [
    {
      title: '函数名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '函数描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '函数标识',
      dataIndex: 'frontendAction',
      key: 'frontendAction',
    },
    {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        render: (type: FunctionType) => (
          <Tag color={type === FunctionType.SYSTEM ? 'blue' : 
                      type === FunctionType.DIRECT ? 'green' : 
                      type === FunctionType.PLUGIN ? 'purple' : 'orange'}>
            {typeToChinese[type]}
          </Tag>
        ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: FunctionStatus) => (
        <Tag color={status === FunctionStatus.PUBLISHED ? 'success' : 
                    status === FunctionStatus.DRAFT ? 'default' : 
                    status === FunctionStatus.DEPRECATED ? 'error' : 'warning'}>
          {statusToChinese[status]}
        </Tag>
      ),
    },
    // {
    //   title: '版本',
    //   dataIndex: 'version',
    //   key: 'version',
    // },
    // {
    //   title: '标签',
    //   dataIndex: 'tags',
    //   key: 'tags',
    //   render: (tags: string[]) => (
    //     <Space>
    //       {tags?.map(tag => (
    //         <Tag key={tag}>{tag}</Tag>
    //       ))}
    //     </Space>
    //   ),
    // },
    {
      title: '是否公开',
      dataIndex: 'isPublic',
      key: 'isPublic',
      render: (isPublic: boolean) => (
        <Tag color={isPublic ? 'green' : 'default'}>
          {isPublic ? '公开' : '私有'}
        </Tag>
      ),
    },
    {
      title: '是否启用',
      dataIndex: 'status',
      key: 'status',
      render: (status: any) => (
        <Tag color={status=='1' ? 'green' : 'default'}>
          {status=='1' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Function) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={handleCreate}>
          创建函数
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={Array.isArray(functionStore.functions) ? functionStore.functions : []}
        rowKey="id"
        loading={functionStore.loading}
        locale={{ emptyText: '暂无数据' }}
      />
      <Modal
        title={ viewType === 'create'
            ? '新建函数'
            : viewType === 'edit'
            ? '编辑函数'
            : '查看函数'}
        open={functionStore.modalVisible}
        onCancel={functionStore.hideModal}
        footer={null}
        width={800}
        bodyStyle={{
          maxHeight: 'calc(100vh - 200px)',
          overflow: 'auto',
          padding: '24px'
        }}
      >
        <FunctionForm
          initialValues={functionStore.editingFunction}
          onSubmit={handleModalOk}
          type={viewType}
          onCancel={functionStore.hideModal}
        />
      </Modal>
    </div>
  );
});

export default FunctionList;